<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace api\user\controller;

use think\Db;
use think\Validate;
use cmf\controller\RestBaseController;

class BrokerController extends RestBaseController
{
    // 用户注册
    public function register()
    {
        $validate = new Validate([
            'name' => 'require',
            'tel_num' => 'require',
            'tel_captcha' => 'require',
            'company' => 'require',
            'subsidiary' => 'require',
        ]);

        $validate->message([
            'name.require'          => '请填写您的姓名！',
            'tel_num.require'          => '请填写您的手机号码！',
            'tel_captcha.require' => '请输入手机验证码！',
            'company.require' => '请填写所在公司！',
            'subsidiary.require' => '请输入分店名称！',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $user = [];

        $findUserWhere = [];

        if (cmf_check_mobile($data['tel_num'])) {
            $user['mobile']          = $data['tel_num'];
            $findUserWhere['mobile'] = $data['tel_num'];
        } else {
            $this->error("请输入正确的手机格式！");
        }

        $errMsg = cmf_check_verification_code($data['tel_num'], $data['tel_captcha']);
        if (!empty($errMsg)) {
            $this->error($errMsg);
        }

        $findUserCount = Db::name("user")->where($findUserWhere)->count();

        if ($findUserCount > 0) {
            $this->error("此手机号码已存在！");
        }


        $user['user_login'] = $data['tel_num'];
        $user['user_nickname'] = $data['name'];
        $more = [
          'company' => $data['company'],
          'subsidiary' => $data['subsidiary'],
        ];
        $user['more'] = json_encode($more, JSON_UNESCAPED_UNICODE);
        $user['create_time'] = time();
        $user['user_status'] = 2;
        $user['user_type']   = 2;
        $user['user_pass']   = '';

        $result = Db::name("user")->insert($user);

        if (empty($result)) {
            $this->error("注册失败,请重试!");
        }

        $this->success("注册成功，请等待审核！");
    }

    // 用户登录 TODO 增加最后登录信息记录,如 ip
    public function login()
    {
        $validate = new Validate([
            'tel_num' => 'require',
            'tel_captcha' => 'require'
        ]);
        $validate->message([
            'tel_num.require' => '请输入手机号码！',
            'tel_captcha.require' => '请输入手机验证码！'
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $findUserWhere = [];
        $findUserWhere['mobile'] = $data['tel_num'];

        $findUser = Db::name("user")->where($findUserWhere)->find();

        if (empty($findUser)) {
            $this->error("用户不存在!");
        } else {

            switch ($findUser['user_status']) {
                case 0:
                    $this->error('您已被拉黑！');
                case 2:
                    $this->error('账户未审核！');
            }

            $errMsg = cmf_check_verification_code($data['tel_num'], $data['tel_captcha']);
            if (!empty($errMsg)) {
                $this->error($errMsg);
            }
        }

        $allowedDeviceTypes = $this->allowedDeviceTypes;

        if (empty($data['device_type']) || !in_array($data['device_type'], $allowedDeviceTypes)) {
            $this->error("请求错误,未知设备!");
        }

        $userTokenQuery = Db::name("user_token")
            ->where('user_id', $findUser['id'])
            ->where('device_type', $data['device_type']);
        $findUserToken  = $userTokenQuery->find();
        $currentTime    = time();
        $expireTime     = $currentTime + 24 * 3600 * 180;
        $token          = md5(uniqid()) . md5(uniqid());
        if (empty($findUserToken)) {
            $result = $userTokenQuery->insert([
                'token'       => $token,
                'user_id'     => $findUser['id'],
                'expire_time' => $expireTime,
                'create_time' => $currentTime,
                'device_type' => $data['device_type']
            ]);
        } else {
            $result = $userTokenQuery
                ->where('user_id', $findUser['id'])
                ->where('device_type', $data['device_type'])
                ->update([
                    'token'       => $token,
                    'expire_time' => $expireTime,
                    'create_time' => $currentTime
                ]);
        }


        if (empty($result)) {
            $this->error("登录失败!");
        }

        $this->success("登录成功!", ['token' => $token, 'user' => $findUser]);
    }

    // 用户退出
    public function logout()
    {
        $userId = $this->getUserId();
        Db::name('user_token')->where([
            'token'       => $this->token,
            'user_id'     => $userId,
            'device_type' => $this->deviceType
        ])->update(['token' => '']);

        $this->success("退出成功!");
    }

    // 用户密码重置
    public function passwordReset()
    {
        $validate = new Validate([
            'username'          => 'require',
            'password'          => 'require',
            'verification_code' => 'require'
        ]);

        $validate->message([
            'username.require'          => '请输入手机号,邮箱!',
            'password.require'          => '请输入您的密码！',
            'verification_code.require' => '请输入数字验证码！'
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $userWhere = [];
        if (Validate::is($data['username'], 'email')) {
            $userWhere['user_email'] = $data['username'];
        } else if (cmf_check_mobile($data['username'])) {
            $userWhere['mobile'] = $data['username'];
        } else {
            $this->error("请输入正确的手机或者邮箱格式!");
        }

        $errMsg = cmf_check_verification_code($data['username'], $data['verification_code']);
        if (!empty($errMsg)) {
            $this->error($errMsg);
        }

        $userPass = cmf_password($data['password']);
        Db::name("user")->where($userWhere)->update(['user_pass' => $userPass]);

        $this->success("密码重置成功,请使用新密码登录!");

    }

    // 会员中心
    public function center () {
      if (empty($this->user)) {
        unauthorized();
      }

      $data = [
        'user' => $this->user,
        'fankui_dianhua' => '041139911321',
      ];

      $this->success('success', $data);
    }

    public function change() {
      if (empty($this->user)) {
        unauthorized();
      }

      $param = $this->request->param();

      $validate = new Validate([
          'company' => 'require',
          'subsidiary' => 'require',
          'name' => 'require',
          'tel_num' => 'require',
      ]);
      $validate->message([
          'company.require' => '公司名称不能为空！',
          'subsidiary.require' => '店铺名称不能为空！',
          'name.require' => '姓名不能为空！',
          'tel_num.require' => '手机号码不能为空！',
      ]);

      $data = $this->request->param();
      if (!$validate->check($data)) {
          $this->error($validate->getError());
      }

      $user = [
        'user_id' => $this->user['id'],
        'company' => $param['company'],
        'subsidiary' => $param['subsidiary'],
        'user_nickname' => $param['name'],
        'mobile' => $param['tel_num'],
      ];

      $find = Db::name("user_auditing")->where('id', $this->user['id'])->find();
      if ($find == null) {
        Db::name("user_auditing")->insert($user);
      } else {
        Db::name("user_auditing")->where('id', $this->user['id'])->update($user);
      }

      $this->success("信息修改已提交，请等待审核");
    }
}
